<template>
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs" v-if="Object.keys(formData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="分摊明细"
                    name="apportionDtl"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="formData"
                                        label-width="150px"
                                        :rules="formDataRules"
                                        ref="formDataRef"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="分摊编号">
                                                    {{ formData.billNo }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="分摊日期">
                                                    <el-date-picker
                                                        v-model="
                                                            formData.billDate
                                                        "
                                                        type="date"
                                                        placeholder="选择日期"
                                                        value-format="yyyy-MM-dd"
                                                        :clearable='false'
                                                    >
                                                    </el-date-picker>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="计划/合同编号"
                                                    prop="contractNo"
                                                >
                                                    <el-input
                                                        v-model="
                                                            formData.contractNo
                                                        "
                                                        readonly
                                                    >
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            @click="
                                                                contractNoClick
                                                            "
                                                        ></i>
                                                    </el-input>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="机构"
                                                    prop="orgName"
                                                >
                                                    {{ formData.orgName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="录入人"
                                                    prop="founderName"
                                                >
                                                    {{ formData.founderName }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="状态"
                                                    prop="state"
                                                >
                                                    {{
                                                         showState(
                                                            formData.state
                                                        )
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-form-item label="备注">
                                                <el-input
                                                    type="textarea"
                                                    :rows="2"
                                                    resize="none"
                                                    placeholder="请输入内容"
                                                    v-model="formData.remarks"
                                                >
                                                </el-input>
                                            </el-form-item>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- 分摊明细 -->
                    <div id="apportionDtlCon" class="con">
                        <div class="tabs-title" id="apportionDtl">分摊明细</div>
                        <div>
                            <div style="padding: 0 10px">
                                <div
                                    style="
                                        padding-left: 10px;
                                        background-color: #f2f2f2;
                                        height: 30px;
                                        line-height: 30px;
                                        border-radius: 1px;
                                    "
                                >
                                    租赁结算明细
                                </div>
                            </div>
                            <div class="e-table">
                                <!-- <div
                                    class="errorMsg"
                                    v-if="errorApportionMsg.length > 0"
                                >
                                    <span>
                                        {{ errorApportionMsg.join(',') }}
                                    </span>
                                </div> -->
                                <el-table
                                    :data="billingData"
                                    border
                                    style="width: 100%;cursor:pointer"
                                    :row-class-name="tableRowClassName"
                                    @selection-change="settlementSelect"
                                    @row-dblclick='settlementDbclick'
                                    ref='billingRef'
                                    :max-height="$store.state.tableHeight"
                                    v-sortTable="{ 'tableData': billingData, '_this': this, 'ref': 'billingRef' }"
                                >
                                    <el-table-column
                                        type="selection"
                                        width="55"
                                    >
                                    </el-table-column>
                                    <!-- <el-table-column
                                        label="操作"
                                        fixed
                                        align="center"
                                    >
                                        <template v-slot="{ row }">
                                            <i
                                                class="el-icon-delete"
                                                style="
                                                    cursor: pointer;
                                                    font-size: 20px;
                                                    color: red;
                                                "
                                                @click="settlementDelete(row)"
                                            ></i>
                                        </template>
                                    </el-table-column> -->
                                    <el-table-column
                                        prop="equipmentNo"
                                        label="设备编号"
                                        min-width="170"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        prop="equipmentName"
                                        label="设备名称"
                                        min-width="130"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        prop="specificationModel"
                                        label="规格型号"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        label="计时单位"
                                        min-width="150"
                                        prop="timingUnit"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        label="累计结算金额(元)"
                                        min-width="150"
                                        prop="cumulativeSettlementAmount"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        prop="otherPrice"
                                        label="其他成本费用(元)"
                                        width="150"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        prop="apportionPrice"
                                        label="成本分摊金额(元)"
                                        width="140"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        label="已分摊金额(元)"
                                        prop="alreadyApportionPrice"
                                        width="120"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        label="剩余未分摊金额(元)"
                                        prop="remainingApportionPrice"
                                        width="140"
                                    >
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                        <div style="height: 60px; text-align: center">
                            <!-- <i class="el-icon-arrow-down" style='font-size: 40px; line-height: 60px;margin-right: 100px;font-weight:700;cursor:pointer;color:#4EBBF3' @click='downClick'></i>
                            <i class="el-icon-arrow-up" style='font-size: 40px; line-height: 60px;margin-left: 100px;font-weight:700;cursor:pointer;color:#4EBBF3' @click='upClick'></i> -->
                            <img class="batchicon" src="@/assets/arrow_down.png" style='margin-right: 200px;cursor:pointer' @click='downClick'/>
                            <img class="batchicon" src="@/assets/arrow_up.png" style='cursor:pointer' @click='upClick'/>
                        </div>
                        <div>
                            <div style="padding: 0 10px">
                                <div
                                    style="
                                        padding-left: 10px;
                                        background-color: #f2f2f2;
                                        height: 30px;
                                        line-height: 30px;
                                        border-radius: 1px;
                                    "
                                >
                                    分摊明细
                                </div>
                            </div>
                            <div class="e-table">
                                <div
                                    class="errorMsg"
                                    v-if="errorApportionMsg.length > 0"
                                >
                                    <span>
                                        {{ errorApportionMsg.join(',') }}
                                    </span>
                                </div>
                                <el-table
                                    :data="allocationData"
                                    border
                                    style="width: 100%"
                                    @selection-change="allocationSelect"
                                    ref='apportionRef'
                                    :max-height="$store.state.tableHeight"
                                    v-sortTable="{ 'tableData': allocationData, '_this': this, 'ref': 'apportionRef' }"
                                >
                                    <el-table-column
                                        type="selection"
                                        width="55"
                                    >
                                    </el-table-column>
                                    <!-- <el-table-column
                                        label="操作"
                                        fixed
                                        align="center"
                                    >
                                        <template v-slot="{ row }">
                                            <i
                                                class="el-icon-delete"
                                                style="
                                                    cursor: pointer;
                                                    font-size: 20px;
                                                    color: red;
                                                "
                                                @click="settlementDelete(row)"
                                            ></i>
                                        </template>
                                    </el-table-column> -->
                                    <el-table-column
                                        prop="equipmentNo"
                                        label="设备编号"
                                        min-width="170"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        prop="equipmentName"
                                        label="设备名称"
                                        min-width="130"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        prop="specificationModel"
                                        label="规格型号"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        label="计时单位"
                                        min-width="150"
                                        prop="timeUnit"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        label="累计结算金额(元)"
                                        min-width="150"
                                        prop="settleAmount"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        prop="outerPrice"
                                        label="其他成本费用(元)"
                                        width="150"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        prop="apportionPrice"
                                        label="成本分摊金额(元)"
                                        width="140"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        label="外包方名称"
                                        prop="outerName"
                                        width="120"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        label="合同"
                                        prop="contractName"
                                        width="140"
                                    >
                                        <template v-slot="{ row }">
                                            <el-input
                                                v-model="row.contractName"
                                                readonly
                                            >
                                                <i
                                                    slot="suffix"
                                                    class="
                                                        el-input__icon
                                                        el-icon-document-copy
                                                    "
                                                    style='cursor:pointer'
                                                    @click="
                                                        contractNameClick(row)
                                                    "
                                                ></i>
                                            </el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="分摊比例%"
                                        prop="apportionProportion"
                                        width="140"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        label="分摊金额(元)"
                                        prop="costApportionPrice"
                                        width="140"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        label="运行时长"
                                        prop="runTime"
                                        width="140"
                                    >
                                        <template slot-scope="scope">
                                            <span
                                                @click="
                                                    runTimeClick(
                                                        scope.row.equipmentNo
                                                    )
                                                "
                                                style="
                                                    color: blue;
                                                    cursor: pointer;
                                                "
                                            >
                                                {{ '累计运行时长' }}
                                            </span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="消耗类型"
                                        prop="consumeType"
                                        width="140"
                                    >
                                        <template slot-scope="{ row }">
                                            <el-select
                                                v-model="row.consumeType"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="item in turnoverData.consumeTypeArr"
                                                    :key="item.id"
                                                    :label="item.name"
                                                    :value="item.id"
                                                ></el-option>
                                            </el-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="甲供类型"
                                        prop="instepType"
                                        width="140"
                                    >
                                        <template slot-scope="{ row }">
                                            <el-select
                                                v-model="row.instepType"
                                                placeholder="请选择"
                                                v-if='row.instepType !== 1'
                                            >
                                                <el-option
                                                    v-for="item in instepTypeList"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                ></el-option>
                                            </el-select>
                                            <span v-else>{{row.instepType === 1 ? '分包扣款' : ''}}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="甲供(元)"
                                        prop="instepPrice"
                                        width="140"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        label="超耗扣款(元)"
                                        prop="exceedDebit"
                                        width="140"
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        label="非甲供扣款(元)"
                                        prop="noInstepDebit"
                                        width="140"
                                    >
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </div>

                    <!-- 附件信息 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <attach-comp
                            :relationId="billid"
                            bucketName="facilitysettle"
                            v-if="objFlag.flag5"
                        />
                        <div class="seize-a-seat" v-else>
                            <i class="el-icon-loading"></i>
                        </div>
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <EquipmentBillingHistory
                            :billType="3030"
                            :billId="billid"
                        ></EquipmentBillingHistory>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="formData.state == 1 || formData.state == 9"
                >打印</el-button
            >
            <exaButtons :auditState="auditState" @exas="exas"  :state='formData.state' :founderId='formData.founderId'></exaButtons>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import {
    showLoading,
    hideLoading,
    openAppClient,
    formatDate
} from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import request from '@/api/settlementManagement/equipmentBilling/rentalCost'
import publics from '@/api/settlementManagement/equipmentBilling/public'
import EquipmentBillingHistory from '@/pages/settlementManagement/equipmentBilling/EquipmentBillingHistory'
import exaButtons from '@/components/common/exaButtons'

export default {
    components: {
        AttachComp,
        EquipmentBillingHistory,
        exaButtons
    },
    data () {
        return {
            tabsName: 'baseInfo',
            billingData: [], // 结算明细
            allocationData: [], // 分摊明细
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            formData: {
                billDate: formatDate(new Date(), 'yyyy-MM-dd'),
                billId: '',
                billNo: '',
                contractNo: '',
                evaluateGrade: 0,
                founderId: '',
                founderName: '',
                leaseOrgId: '',
                leaseOrgName: '',
                leaseSettleId: '',
                leaseSettleNo: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDesciption: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                remarks: '',
                settleAmount: 0,
                state: 0,
                workId: ''
            },
            objFlag: {
                flag5: false
            },
            billid: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转,
            formDataRules: {
                // contractNo: [
                //     {
                //         required: true,
                //         message: '请选择计划/合同编号',
                //         trigger: 'blur'
                //     }
                // ],
            },
            isBatch: true,
            MouseEnterId: null,
            MouseEnterIdF: null,
            auditState: {},
            auditParams: {
                billId: '',
                billType: '3030',
                freeNextUnitIndex: null,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            },
            nullifyParams: {
                // 作废
                billId: this.$route.query.billid,
                billType: '3030',
                nullifyDescription: '',
                nullifyReason: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: ''
            },
            errorList: [], //控制导航栏感叹号的显示
            errorApportionMsg: [], // 分摊明细
            isBaseCurRate: true,
            isSubmit: false,
            contractQuery: {
                orgId: '',
                secondPartyId: ''
            },
            settlementSelectList: [],
            apportionSelectList: []
        }
    },
    computed: {
        ...mapState({
            instepTypeList: state => state.settlementManagement.instepTypeList,
            turnoverData: state => state.turnover.turnoverData
        }),
        //状态

        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 20 - this.lastConHeight
        }
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        }
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.billid = this.$route.query.billid
        this.auditParams.billId = this.$route.query.billid
        this.contractQuery.orgId = this.orgId
        this.getAllData()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'apportionDtl', 'accessory', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop + 20
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 50 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setPopConfirm', 'setAuditParams', 'setSelectedInfo']),
        //如果是新增后,直接跳转到编辑页的情况需要跳转到第二个标签
        scorllDtl () {
            if (this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        getAllData () {
            showLoading()
            Promise.all([
                this.getBasicInfo(), //进入页面就获取基本信息数据
                this.getAttach(), // 附件列表
                this.getUnitInfo() // 获取按钮状态
            ]).finally(() => {
                hideLoading()
            })
        },

        //获取基本信息数据
        async getBasicInfo () {
            let data = await request.getBasicInfo(this.billid)
            this.formData = data
            await this.getLeaseSet() //  获取结算明细
        },

        // 计划/合同编号
        async contractNoClick () {
            let res = await request.getContractNo(this.formData.leaseSettleId)
            if (res.length < 1) {
                this.contractChange()
                this.billingData = []
                this.allocationData = []
                return
            }
            let data = res[0]
            if(this.formData.contractNo !== data.billNo) {
                this.formData.leaseSettleId = data.billId // 用于显示已选数据的传参
                this.formData.contractNo = data.billNo // 计划/合同编号
                // 获取租赁结算明细
                await this.getLeaseSet()
                this.allocationData = []
            }
        },
        contractChange () {
            this.formData.leaseSettleId = ''
            this.formData.contractNo = ''
        },
        // 双击租赁结算明细
        async settlementDbclick (row) {
            console.log(row)
            let arr = await request.downApportion(
                [row.id]
            )
            arr.forEach(item => {
                let isPush = this.allocationData.every(it =>item.id !== it.id)
                if(isPush) {
                    this.allocationData.push(item)
                }
            })
        },
        // 租赁结算多选框中的数据
        settlementSelect (selection) {
            this.settlementSelectList = selection
        },
        // 向下分摊明细
        async downClick () {
            let ids = this.settlementSelectList.map(item => item.id)
            // this.setSelectedInfo(ids)
            // openAppClient('/showSelectedData', '传参')
            await this.downApportion(ids)
            this.$refs.billingRef.clearSelection()
        },
        // 分摊明细多选框中的数据
        allocationSelect (selection) {
            this.apportionSelectList = selection
        },
        // 向上取消分摊明细
        upClick () {
            // this.billingData.forEach(item => {
            //     let index = this.apportionSelectList.findIndex(it => {
            //         if (it.dtlId === item.id) {
            //             // 如果相等,则在结算明细中取消背景色,并且在分摊明细中删除这条数据
            //         }
            //     })
            //     this.allocationData.splice(index, 1)
            // })
            this.apportionSelectList.forEach(item => {
                let index = this.allocationData.findIndex(it => item.id === it.id)
                this.allocationData.splice(index, 1)
            })
            this.$refs.apportionRef.clearSelection()
        },
        // 租赁结算的背景色
        tableRowClassName ({ row }) {
            // 如果租赁结算明细中的数据都在分摊明细中,则租赁结算明细的这条数据背景色为绿色;否则只要有一条数据在分摊明细中,背景色就为橙色;一条都不在分摊明细中就没有背景色
            // 通过关联id去获取分摊明细中和租赁结算明细相关联的数据,计算分摊明细的分摊金额是否等于关联数据的未分摊金额,如果相等就绿色;不相等再看是否有一条在分摊明细中,若有则橙色;若没有则无背景色
            this.billingData.forEach((item, index) => {
                let billingArr = this.allocationData.filter(its => item.id === its.dtlId)
                let amountSum = billingArr.reduce((prev, c) => prev += (+c.costApportionPrice || 0), 0)
                if(+item.remainingApportionPrice === +amountSum) {
                    this.$set(this.billingData[index], 'bgc', 'g')
                }else {
                    let isOrange = this.allocationData.some(it => item.id === it.dtlId)
                    if(isOrange) {
                        this.$set(this.billingData[index], 'bgc', 'o')
                    }else {
                        this.$set(this.billingData[index], 'bgc', '')
                    }
                }

            })
            if(row.bgc === 'o') {
                return 'orange'
            }else if(row.bgc === 'g') {
                return 'green'
            }
            return ''
        },

        // --------------------------------分摊明细----------------------------

        // 获取结算明细
        async getLeaseSet () {
            this.billingData = await request.getLeaseSet(
                this.formData.leaseSettleId
            )
        },
        // 点击向下箭头时,获取当前租赁结算中已分摊的分摊明细
        // async getCostAllocation (id) {
        //     this.allocationData = await request.getCostAllocation(
        //         id
        //     )
        //     // this.setSelectedInfo(this.allocationData)
        //     // openAppClient('/showSelectedData', '选择结果')
        // },
        // 点击向下箭头时,获取当前租赁结算中剩余未分摊的明细
        async downApportion (id) {
            let arr = await request.downApportion(
                id
            )
            console.log(arr)
            if(arr.length > 0) {
                arr.forEach(item => {
                    let isPush = this.allocationData.every(it =>item.id !== it.id)
                    if(isPush) {
                        this.allocationData.push(item)
                    }
                })
            }

            // this.setSelectedInfo(this.allocationData)
            // openAppClient('/showSelectedData', '选择结果')
        },
        // 分摊明细-弹窗选择合同
        async contractNameClick (row) {
            let res = await request.contractNameClick(
                this.contractQuery,
                row.contractId ? [row.contractId] : []
            )
            row.contractId = res[0].contractId
            row.contractNo = res[0].contractNumber
            row.contractName = res[0].contractName
            // 根据选择的合同查询甲供清单
            let aOfferingList = await request.aOffering(row.contractId)
            let isExist = aOfferingList.some(item =>{
                if(item.equipmentName === row.equipmentName) {
                    // 如果甲供清单中包含当前行设备,且当前行设备的分摊金额超过找到这条甲供清单甲供的设计金额，消耗类型为超甲供扣款,否则为甲供
                    if(+row.costApportionPrice > +item.amount) {
                        row.consumeType = 1
                        // 如分摊金额超过甲供数据,则甲供数据为合同甲供设计数据
                        row.instepPrice = item.amount
                        // 如分摊金额超过甲供数据，则超耗扣款为：该分包商分摊金额-合同甲供设计金额
                        row.exceedDebit = +row.costApportionPrice - +item.amount
                    }else {
                        row.consumeType = 0
                        // 分摊金额未超合同甲供，则甲供数据为分摊金额
                        row.instepPrice = row.costApportionPrice
                        // 如分摊金额未超合同甲供，则超耗扣款为0
                        row.exceedDebit = 0
                    }
                    return true
                }else {
                    return false
                }
            })
            // 如果甲供清单中没有当前行设备,消耗类型为非甲供扣款,且甲供类型为分包扣款
            if(!isExist) {
                row.consumeType = 2
                row.instepType = 1
                // 当甲供类型为分包扣款时，非甲供扣款金额为分摊金额
                row.noInstepDebit = row.costApportionPrice
            }else {
                row.instepType = ''
                row.noInstepDebit = 0
            }
        },

        // 点击累计运行时长
        async runTimeClick (equipmentNo) {
            // this.setSelectedInfo(equipmentNo)
            // openAppClient('/showSelectedData', '传参')
            await request.runTimeClick(equipmentNo)
        },

        // -------------------在点击下面几个按钮前,需要做前置判断-------------------------
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x => x === name)
            if (index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        // 设置分摊明细有错误时在表格上面显示的错误信息
        setErrorApportion (msg) {
            let index = this.errorApportionMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorApportionMsg.push(msg)
            }
        },

        // 点击左边的Tab标签
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //保存基本信息时需要检测的
        basicInfoSave () {
            return new Promise((resolve, reject) => {
                this.$refs.formDataRef.validate(valid => {
                    if (valid) {
                        request
                            .basicInfoSave(this.formData)
                            .then(() => {
                                this.clearError('baseInfo')
                                resolve()
                            })
                            .catch(err => {
                                reject(err)
                                this.setError('baseInfo')
                            })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })
        },
        // 保存分摊明细
        costAllocationUpdate () {
            this.errorApportionMsg = []
            return new Promise((resolve, reject) => {
                if (this.isSubmit) {
                    // 如果点击的是提交审核才需要判断分摊明细是否为空,为空时不能提交审核
                    if (this.allocationData.length < 1) {
                        this.setErrorApportion('请选择需分摊的数据')
                        this.setError('apportionDtl')
                        reject('分摊明细错误')
                        return
                    } else {
                        let isData = this.allocationData.every(
                            item => item.changeType === -1
                        )
                        if (isData) {
                            this.setErrorApportion('请选择需分摊的数据')
                            this.setError('apportionDtl')
                            reject('分摊明细错误')
                            return
                        }
                    }
                }
                this.allocationData.forEach(item => {
                    if (item.changeType !== -1) {
                        !item.equipmentNo
                            ? this.setErrorApportion('请填写设备编号')
                            : ''
                        !item.equipmentName
                            ? this.setErrorApportion('请填写设备名称')
                            : ''
                        !item.specificationModel
                            ? this.setErrorApportion('请填写规格型号')
                            : ''
                        !item.timeUnit
                            ? this.setErrorApportion('请选择计时单位')
                            : ''
                        !item.settleAmount
                            ? this.setErrorApportion('请选择累计结算金额')
                            : ''
                        !item.outerPrice
                            ? this.setErrorApportion('请填写其他成本费用')
                            : ''
                        !item.apportionPrice
                            ? this.setErrorApportion('请填写成本分摊金额')
                            : ''
                        !item.outerName
                            ? this.setErrorApportion('请填写外包方名称')
                            : ''
                        !item.contractName
                            ? this.setErrorApportion('请填写合同')
                            : ''
                        !item.apportionProportion
                            ? this.setErrorApportion('请填写分摊比例')
                            : ''
                        !item.apportionPrice
                            ? this.setErrorApportion('请填写分摊金额')
                            : ''
                        !item.runTime
                            ? this.setErrorApportion('请填写运行时长')
                            : ''
                        !item.consumeType
                            ? this.setErrorApportion('请填写消耗类型')
                            : ''
                        !item.instepType
                            ? this.setErrorApportion('请填写甲供类型')
                            : ''
                    }
                })
                if (this.errorApportionMsg.length > 0) {
                    this.setError('apportionDtl')
                    reject('分摊明细错误')
                    return
                } else {
                    request
                        .costAllocationUpdate(this.allocationData)
                        .then(() => {
                            this.getLeaseSet()
                            this.clearError('apportionDtl')
                            resolve()
                        })
                        .catch(err => {
                            this.errorApportionMsg[0] = err.message
                            this.setError('apportionDtl')
                            reject(err)
                        })
                }
            })
        },

        // 保存所有数据
        saveAll () {
            showLoading()
            this.errorList = []
            Promise.all([this.basicInfoSave(), this.costAllocationUpdate()])
                .then(() => {
                    hideLoading()
                    this.clientPop('suc', '保存成功')
                })
                .catch(() => {
                    // this.clientPop('err', '保存失败', () => {
                    this.scorllError()
                    // })
                })
                .finally(() => {
                    hideLoading()
                })
        },

        // 提交审核
        submitReview () {
            showLoading()
            this.errorList = []
            Promise.all([this.basicInfoSave(), this.costAllocationUpdate()])
                .then( () => {
                    publics
                        .commitAudit(this.auditParams)
                        .then(() => {
                            this.clientPop('suc', '提交成功', this.handleClose)
                        })
                        .catch(() => {
                            // this.clientPop('err', '提交失败', () => {
                            this.scorllError()
                            // })
                        })
                })
                .catch(() => {
                    // this.clientPop('err', '提交失败', () => {
                    this.scorllError()
                    // })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 审核
        onAudit () {
            showLoading()
            this.setAuditParams(this.auditParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/exaDialog', '填写审核意见', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                publics
                    .audit(auditParams)
                    .then(() => {
                        this.clientPop('suc', '审核成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },

        // 撤销审核
        undoAudit () {
            showLoading()
            publics
                .undoAudit(this.auditParams)
                .then(() => {
                    this.clientPop('suc', '撤回成功', this.handleClose)
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                publics
                    .nullify(auditParams)
                    .then(() => {
                        this.clientPop('suc', '作废成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },
        // 删除
        basicInfoDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作！',
                () => {
                    showLoading()
                    request
                        .basicInfoDelete(this.billid)
                        .then(() => {
                            this.clientPop('suc', '删除成功', this.handleClose)
                        })
                        .finally(() => {
                            hideLoading()
                        })
                }
            )
        },

        // ---------------------------下面按钮---------------------------
        // 获取按钮状态
        async getUnitInfo () {
            this.auditState = await publics.getCurrentUnitInfo(
                this.auditParams
            )
        },

        // 点击下面几个不同的按钮做不同的操作
        exas (arg) {
            if (arg === 'submit') {
                this.isSubmit = false
                this.saveAll() // 保存所有数据
            } else if (arg === 'submitCommit') {
                this.isSubmit = true
                this.submitReview() // 保存并提交
            } else if (arg === 'audit') {
                this.onAudit() // 审核
            } else if (arg === 'undoAudit') {
                this.undoAudit() // 撤销审核
            } else if (arg === 'nullify') {
                this.nullify() // 作废
            } else if (arg === 'deleteData') {
                this.basicInfoDelete() // 删除
            }
        },

        //取消按钮
        handleClose () {
            this.$router.replace('/rentalCostSetList')
        },

        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('auditHistoryCon')) {
                    const lastConHeight =
                        document.getElementById('auditHistoryCon').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },

        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        showState (state) {
            const _state = this.$store.state.equip.equipData.settleState
            const obj = _state.find(x => x.value === Number(state))
            return obj.label
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
::v-deep.el-table .orange {
    background-color: #FFA40D;
}
::v-deep.el-table .green {
    background-color: #06AD36;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
::v-deep .el-table__fixed{
        height: 100% !important
}
</style>
